

class RedGreenRefactoring

  class TestCase < Assertions

    attr_accessor :errors

    def self.run
      self.new.run
    end
    
    def initialize reporter = TestReporter
      if reporter ==  TestReporter
        reporter = reporter.new
      end
      if reporter.is_a? TestReporter
        @_reporter = reporter
      else
        raise "The first parameter should be a of TestReporter! (was #{reporter.inspect}"
      end
    end
    
    #called before every test
    def setup; end
    #called after every test
    def teardown; end


    def run
      @_reporter.test_case(self) do
        run_test_methods
      end
      @_reporter
    end

    def pass
      @_reporter.pass
    end

    def fail exception
      if exception.is_a? String
        begin
          raise exception
        rescue Exception => e
          exception = e
        end
      end
      @_reporter.fail exception
    end

    def error exception
      @_reporter.error exception
    end

    private

    def run_test_methods
      self.methods.each do |method|
        if method[0,4] == "test"
          run_test_method method
        end
      end
    end
    
    def run_test_method method_name
      begin
        @_reporter.test(method_name)
        setup
        self.send(method_name)
      rescue AssertionFail => e
        fail e
      rescue Exception => e
        error e
      ensure
        teardown
      end
    end
  end
  
end  





